<template>
  <a-card :bodyStyle="{display:'flex',padding:'0px'}" 
  style="margin:5px;"
  class=""
  >
    <div slot="title" class="title">
      <!-- <span>报文组管理</span> -->
      <a-icon style="position: absolute;right: 20px;" class="anticon-ok anticon-action"
        title="上传报文组" 
        @click="isupload=true;modalShow=true" 
        type="plus" 
      />
    </div>
    <a-table
      :loading="!dataList.length"
      :columns="columns"
      :data-source="dataList"
      :rowKey="(record,index) => JSON.stringify({id:record.id,index})"
      :bordered="true"
      :pagination="false"
      :locale="{filterConfirm: '确认',filterReset: '重置'}"
      :scroll="{y:'calc(100vh - 131px)'}"
      :customRow="rowClick"
      :rowClassName="(record) => { 
        const { name,description } = record.edit
        return name||description? 'selected' : 'normal' }"
    >
      <template slot="name" slot-scope="value,item" @click.stop
      >
        <a-input v-if="item.edit.name" 
        :defaultValue="value"
        @click.stop
        @pressEnter="(e)=>{ changeMessage(e,item,'name') }"
        />
        <span 
         @dblclick.stop = "item.edit.name = !item.edit.name"
         v-else>{{value}}</span>
      </template>
      <template slot="describe" slot-scope="value,item" @click.stop>
        <a-input v-if="item.edit.describe" 
        :defaultValue="value"
        @click.stop
        @pressEnter="(e)=>{ changeMessage(e,item,'describe') }"
        />
        <span
         @dblclick.stop = "item.edit.describe = !item.edit.describe"
         v-else>{{value}}</span>
      </template>
      <span slot="analysis"  slot-scope="analysis,item" :style="{color:['maroon','orange','green'][analysis+1]}">
        {{tagDict.analysis[analysis]}}
      </span>
      <span slot="target" slot-scope="target,item" :style="{color:['maroon','orange','green'][target+1]}">
        {{tagDict.target[target]}}
      </span>
    </a-table>
    <!-- 上传报文组 && 查看报文组信息||报文组操作 -->
    <a-modal
      :visible="modalShow"
      :title="isupload?'上传报文组':`报文组详情[上传于${recordInfo.time}]`"
      :maskClosable="!((fileList && fileList.length ) || (targetList && targetList.length ) || taskLoading)"
      :closable="!taskLoading"
      :keyboard="!taskLoading"
      @cancel="modalClose"
      :width="(isupload?fileList.length:targetList.length)?'90%':'520px'"
      :bodyStyle="{display:'flex',padding:'0',overflowX:'hidden',height:'350px',position:'relative'}"
    >
      <template slot="footer">
        <a-button type="danger" :disabled="taskLoading" ghost @click="modalClose">
          取消
        </a-button>
        <!-- <a-button icon="delete" type="danger" :disabled="taskLoading" ghost @click="()=>{
          if(isupload) fileList=[]
          else delmessage()
        }" >
          {{isupload?'清空上传列表':'删除报文组'}}
        </a-button> -->
        <a-button v-if="!isupload" icon="delete" type="danger" :disabled="taskLoading" ghost 
        @click="delmessage" >
          删除报文组
        </a-button>
        <a-button type="primary" ghost :disabled="taskLoading" :loading="subloading" @click="()=>{
          if(isupload) uploadMessage()
          else choosesure()
        }">
          {{isupload?'上传':'确认'}}
        </a-button>
        <!-- <a-button type="primary" ghost :loading="taskLoading" @click="">
          确认
        </a-button> -->
      </template>
    
      <a-spin 
        v-if="taskLoading" 
        :style="{width:'100%',position:'absolute',left:'0',top:'0',background: '#0002',zIndex: '999',display: 'flex',height: '100%'}"
        size="large"
      />
      <div style="width:470px;margin:25px;flex-shrink: 0;display: flex;flex-direction: column;">
        <template v-if="isupload">
          <div class="modal-body-div">
            <span class="ant-form-item-required">数据备注</span>
            <a-input v-model="fileInfo.name" placeholder="给数据集起个名字吧"/>
          </div>
          <div class="modal-body-div" style="height:auto;margin: 10px 0;">
            <span class="ant-form-item-required">描述信息</span>
            <a-textarea v-model="fileInfo.describe" placeholder="描述一下数据集吧" :autoSize="{ minRows: 1, maxRows: 5 }" />
          </div>
          <div class="modal-body-div" style="height:auto;margin: 10px 0;">
            <span class="ant-form-item-required">文件路径</span>
            <a-input v-model="fileInfo.path" placeholder="复制报文组所在路径" />
          </div>
          <!-- 
          文件上传文件
          <a-upload-dragger
            :file-list="fileList"
            :before-upload="(file)=>{
              const { name } = file
              const type = name.substring(name.lastIndexOf('.'))
              if(fileType === null)
                fileType = type
              if (type === fileType)
                fileList = [...fileList, file]
              else
                $message.warn({
                  content:`${name}与第一次上传文件类型不同`,
                  key:'DifferentFromTheLastOne'
                })
              return false
            }"
            style="height: auto;flex:1"
            accept=".html"
            :showUploadList="false"
            multiple
          >
            <p class="ant-upload-drag-icon">
              <a-icon type="inbox" />
            </p>
            <p class="ant-upload-text">
              单击或拖动文件到此区域上传
            </p>
            <p class="ant-upload-hint">
              支持单个或批量上传
            </p>
          </a-upload-dragger> -->
        </template>
        <template v-else>
          <!-- <a-divider orientation="left" style="margin: 0;">基本信息</a-divider> -->
          <div class="modal-body-div">
            <span class="ant-form-item-required">数据备注</span>
            <a-input v-model="recordInfo.name" placeholder="给数据集起个名字吧"/>
          </div>
          <div class="modal-body-div" style="height:auto;margin: 10px 0;">
            <span class="ant-form-item-required">描述信息</span>
            <a-textarea v-model="recordInfo.describe" placeholder="描述一下数据集吧" :autoSize="{ minRows: 1, maxRows: 5 }" />
          </div>
          <!-- <span v-if="recordInfo.info">{{recordInfo.info.analysis}}</span> -->
          <a-divider orientation="left" style="margin: 0;">操作</a-divider>
          <a-button icon="clock-circle" v-if="recordInfo.info && recordInfo.info.analysis!=1"
            :disabled="recordInfo.info && Boolean(recordInfo.info.analysis)"
            style="margin:5px 0;" @click="_dataAnalysisi"
          >
            {{Boolean(recordInfo.info.analysis)?'解析中...请等待任务完成':'解析报文组'}}
          </a-button>
          <template v-else>
            <a-button style="margin:5px 0;" icon="download" @click="_getTargetFile">
              导出报文组ID
            </a-button>
            <a-button
              v-if="recordInfo.info &&recordInfo.info.target && !targetList.length"
              icon="eye" style="margin:5px 0;"
              @click="priviewTarget(false)"
              :disabled="recordInfo.info &&recordInfo.info.target===-1"
            >
              查看目标变量
            </a-button>
            <a-upload
              class="uploadTarget"
              accept=".xlsx,.xls,.csv"
              :file-list="fileList"
              :beforeUpload="(file)=>{
                fileList = [file]
                return false
              }"
              :remove="()=>{fileList = []}"
            >
              <a-button
                :disabled="recordInfo.info &&recordInfo.info.target===-1"
                style="margin:5px 0;width:100%" icon="upload">
                {{((recordInfo.info &&recordInfo.info.target)? '重新':'')+'导入目标变量'}}
              </a-button>
            </a-upload>
          </template>
        </template>
      </div>
      <!-- 右部分 -->
      <a-list
        v-if="isupload"
        :data-source="fileList"
        :pagination="listpagination"
        :style="{flex:1,overflowX:'hidden'}"
      >
        <p slot="header" style="font-weight: 700;padding-left: 30px;" class="nowarp">
          文件列表预览
        </p>
        <a-list-item slot="renderItem" slot-scope="item, index">
          <p class="nowarp">{{item.name}}</p>
          <a-button type="link" @click="()=>{
            fileList.splice(index,1)
            $message.warning({content:`移除${item.name}`,key:'yichuwenjian'})
          }">移除</a-button>
        </a-list-item>
      </a-list>
      <template v-else>
        <div class="hidden-scroll" :style="{flex:1,overflowX:'hidden'}">
          <div v-for="item in 
          [{
            reportno:'REPORT_NO',
            target1:'TARGET_1',
            target2:'TARGET_2',
            target3:'TARGET_3',
            target4:'TARGET_4',
            target5:'TARGET_5'
          }].concat(targetList)" 
            class="show-targetlist"
          >
            <span >{{item.reportno}}</span>
            <span v-if="targetNum>=1">{{item.target1}}</span>
            <span v-if="targetNum>=2">{{item.target2}}</span>
            <span v-if="targetNum>=3">{{item.target3}}</span>
            <span v-if="targetNum>=4">{{item.target4}}</span>
            <span v-if="targetNum>=5">{{item.target5}}</span>
          </div>
          
          <a-button v-if="showLoadingMore" @click="priviewTarget(true)"
          style="margin: 5px 0;width: 100%;"
          >加载更多</a-button>
        </div>
      </template>
      <div style="display:flex;flex-direction: column;">
        
        <a-tooltip 
          placement="left" 
          :title="`导入信息\n 报文组数量：${targetInfo.message_total}\n 上传目标变量数量：${targetInfo.total}\n 匹配到的行数：${targetInfo.T_total}\n 未匹配到的行数：${targetInfo.F_total}`"
        >
          <a-icon
            type="info-circle" 
            class="pack-up-target"
            style="border-bottom: 1px solid #0003;"
          />
        </a-tooltip>
        <a-icon v-if="targetList" 
          @click="priviewTarget(false)"
          title="收起"
          style="height: 100%;"
          class="pack-up-target" 
          type="double-left"
        />
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { mapGetters,mapActions } from 'vuex'
import { 
  RANDOM,
  exportFile,
  groupBy,
  dateFormat,
  getWeekday,
} from '@/utils/functions'
import { 
  getFileList,
  addFile,
  deleteFile,
  changeFileInfo,
  dataAnalysisi,
  getUserInfo,
  getTargetFile,
  addTargetFile,
  getTargetList,
  getAnaStatus
  } from '@/axios/api'

export default{
  data(){
    return{
      modalShow:false,
      modalClose:()=>{
        this.modalShow = false
        this.fileList = []
        this.targetList = []
      },
      taskLoading:false,
      subloading:false,
      fileList:[],
      targetList:[],
      targetInfo:{},
      showLoadingMore:true,
      targetNum:0,
      current:1,
      isupload:false,
      listpagination:{
        pageSize: 10,
        defaultCurrent:1,
        simple:true
      },
      fileType:null,
      fileInfo:{
        name:'',
        describe:''
      },
      tagDict: Object.freeze({
        analysis:{
          '1':'已解析',
          '0':'未解析',
          '-1':'解析中...',
          title:`未解析的报文组\n不能生成样本`,
        },
        target:{
          '1':'已导入',
          '0':'未导入',
          '-1':'导入中',
          title:`导入目标变量...\n没导入的...`,
        },
      }),
      columns:[
        {
          title: '报文组',
          dataIndex: 'name',
          scopedSlots: {customRender: 'name'},
          ellipsis:true,
          align:'left',
          width:150,
          sorter: (a, b) => a.name.localeCompare(b.name),
        },{
          title: '上传时间',
          dataIndex: 'time',
          ellipsis:true,
          align:'right',
          sorter: (a, b) => new Date(a.time) - new Date(b.time),
          width:200,
        },{
          title: '征信报告数量',
          dataIndex: 'total',
          ellipsis:true,
          align:'right',
          sorter: (a, b) => a.total - b.total,
          width:120,
        },{
          title: '解析状态',
          dataIndex: 'info.analysis',
          scopedSlots: {customRender: 'analysis'},
          ellipsis:true,
          align:'right',
          width:100,
          filters:[
            { text: '已解析', value: 1 },
            { text: '未解析', value: 0 },
          ],
          onFilter: (value, record) => record.info.analysis === Boolean(value),
        },{
          title: '目标变量',
          dataIndex: 'info.target',
          scopedSlots: {customRender: 'target'},
          ellipsis:true,
          align:'right',
          width:100,
          filters:[
            { text: '已导入', value: 1 },
            { text: '未导入', value: 0 },
          ],
          onFilter: (value, record) => record.info.target === Boolean(value),
        },{
          title: '描述',
          dataIndex: 'describe',
          scopedSlots: {customRender: 'describe'},
          ellipsis:true,
          align:'left',
        }
      ],
      clicktimer:null,
      recordInfo:{},
      rowClick:record => ({
        on: {
          dblclick:()=>{
            clearTimeout(this.clicktimer)
            const { name,describe } = record.edit
            if(name || describe)
              record.edit = {name:false,describe:false}
            if(!name && !describe){
              record.edit = {name:true,describe:true}
            }
          },
          click:()=>{
            clearTimeout(this.clicktimer)
            this.clicktimer = setTimeout(()=>{
              console.log({record})
              this.recordInfo = this._cloneDeep(record)
              this.isupload=false
              this.modalShow=true
            },300)
          }
        }
      }),
      dataList:[],
      inter:null,//计时器
    }
  },
  created(){
    const { token } = this.$store.getters
    getUserInfo({token}).then(response => {
      const { data:{ dataList } } = response
      this.dataList = dataList.reverse().map(e=>{
        let {analysis,target,feature} = e.info
        if(!e.total) e.total = "读取中..."
        e.edit={
          name:false,
          describe:false,
        }
        return e
      })
      console.log(this.dataList)
    }).catch(() => {})
    this.inter = setInterval(()=>{
      // if(this.parsingList){
        const {analysis,target} = this.parsingList
        if(analysis.length || target.length)
          this._getAnaStatus(analysis.join(","),target.join(","))
      // }
    },2000)
  },
  methods:{
    async changeApi(id,key,value,item){
      const msg = this.$message.loading({content:`${key}修改中...`,duration:0})
      await changeFileInfo({id,key,value}).then(e=>{
        this.$message.success(`${key}修改成功`)
        item[key] = value
        item.edit[key] = false
      }).catch(()=>{}).then(()=>{msg()})
    },
    changeMessage(e,item,attr){
      const {_value} = e.srcElement || e.target
      const source = item[attr]
      if (_value === source) { item.edit[attr] = false;return }
      const { id } = item
      this.changeApi(id,attr,_value,item)
    },
    async uploadMessage(){
      const { name,describe,path} = this.fileInfo
      if(!name || !describe || !path) {
        this.$message.warn("请填写备注和描述信息")
        return
      }
      /**
       * 这里需要做一下路径判断，文件判断等
       */
      this.subloading = true
      this.taskLoading = true
      // const postFormData = new FormData()
      // this.fileList.forEach(file => {
      //   postFormData.append('fileList', file)
      // })
      const time = dateFormat('Y-M-D h:m:s',new Date())
      // const total = "读取中..."
      await addFile({name:name.trim(),describe,path})
      .then(e=>{
        const { data:{id,total} } = e
        this.$message.success("上传成功")
        this.fileInfo = {name:'',describe:''}
        this.fileList = []
        this.dataList.unshift({
          id,time,name,describe,total,
          info:{analysis:0,target:0},
          edit:{name:false,describe:false}
        })
        this.modalShow = false
      }).catch(()=>{})
      this.taskLoading = false
      this.subloading = false
    },
    async uploadTarget(id,name,fileList,item){
      const postFormData = new FormData();
      fileList.forEach(file => {postFormData.append('multipartFiles', file)})
      addTargetFile({samplId:id,name},postFormData).then(e=>{
        console.log({e})
      })
      setTimeout(()=>{
      	this.$message.success("任务提交成功")
      	// info.analysis = -1
      	// this.recordInfo.info = info
      	// this.dataList[index].info = info
      	// this.$set(this.dataList,index,this.dataList[index])
        this.fileList = []
        // this.$message.success("上传任务提交成功")
        item.info.target = -1
      },50)
    },
    async choosesure(){
      const { recordInfo:{name,describe,id},fileList,dataList } = this
      if(!name || !describe) {
        this.$message.warn("请填写备注和描述信息")
        return
      }
      const item = dataList.find(e=>e.id == id)
      const { name:oldName,describe:oldDesc } = item
      this.taskLoading = true
      if(name != oldName) await this.changeApi(id,'name',name,item)
      if(describe != oldDesc) await this.changeApi(id,'describe',describe,item)
      if(fileList && fileList.length) await this.uploadTarget(id,name,fileList,item)
      this.taskLoading = false
      this.modalShow = false
    },
    async delmessage(){
      this.taskLoading = true
      const { id } = this.recordInfo
      const index = this.dataList.findIndex(e=>e.id===id)
      await deleteFile({id}).then(e=>{
        this.dataList.splice(index,1)
        this.modalShow = false
      }).catch(()=>{})
      this.taskLoading = false
    },
    async _getTargetFile(){
      this.taskLoading = true
      const { id,name } = this.recordInfo
      const loadingmsg = this.$message.loading({content:`${name} - 导出中`,duration:0})
      await getTargetFile({id}).then(request=>{
        if(Object.prototype.toString.call(request)!='[object Blob]'){
          this.$message.warn(`请求返回值异常`)
        }else{
          const blob = new Blob([request],{type: 'application/csv'})
          const url = window.URL.createObjectURL(blob)
          this.$message.success(`${name} - 导出成功`)
          const fileName = `样本集:${name}-目标变量ID.csv`
          exportFile(url,fileName)
        }
      }).catch(()=>{})
      this.taskLoading = false
      loadingmsg()
    },
    async _dataAnalysisi(){
      this.taskLoading = true
      const msg = this.$message.loading("报文组解析中...")
      const { id,info } = this.recordInfo
      const index = this.dataList.findIndex(e=>e.id===id)
      dataAnalysisi({id})
      setTimeout(()=>{
				this.$message.success("任务提交成功")
				info.analysis = -1
				this.recordInfo.info = info
				this.dataList[index].info = info
				this.$set(this.dataList,index,this.dataList[index])
			},50)
      msg()
      this.taskLoading = false
    },
    async priviewTarget(loadMore){
      let { targetList,recordInfo:{ id } } = this
      if(!loadMore && targetList && targetList.length){
        this.targetList = []
        this.targetNum = 0
        this.targetInfo = {}
        return
      }
      this.taskLoading = true
      const from = targetList.length
      const length = 25
      await getTargetList({id,from,length}).then(e=>{
        let { targetList:{targetNum,listData},targetInfo } = e.data
      	if(this.targetNum < targetNum)
      		this.targetNum = targetNum
      	if(listData.length != length){
          this.showLoadingMore = false
        }
        if(targetInfo) this.targetInfo = targetInfo
        this.targetList = [...targetList,...listData] 
        console.log({targetList})
      }).catch(e=>{console.log(e)})
      this.taskLoading = false
    },
    async _getAnaStatus(analysis,target){
			console.log({analysis,target})
      const {data:result} = await getAnaStatus({analysis,target})
      //*没法mock
      for(let item of result){
        const {id,caozuo} = item
        // const ok = this.dataList.find(e=>e.id === id)
        const ok = this.dataList.find(e=>e.id == id)
        if(ok){
          ok.info[caozuo] = 1
          this.$set(this.dataList,index,ok)
          this.$message.success(ok.name+'-任务执行完成')
        }
      }
    }
  },
  beforeRouteLeave (to, from, next) {//后置
    this.$store.commit('setDataList',this.dataList)
    clearInterval(this.inter)
    next()
  },
  computed:{
    parsingList(){
      const { dataList } = this
      const post = {
          analysis:[],
          target:[]
        }
      for(let item of dataList){
        // debugger
        const {id,info:{analysis,target}} = item
        if(analysis===-1) post.analysis.push(id)
        if(target===-1) post.target.push(id)
      }
      console.log("任务进行中的id:",{post})
      return post
    }
  }
}
</script>

<style lang="less" scoped>
@titleHeight:40px;
.pack-up-target{
  display: flex !important;
  align-items: center;
  transition: all .5s;
  cursor: pointer;
  &:hover{
    background: #fafafa;
    color: rgb(61,120,205);
  }
}
.samples{
  display: flex;
  align-content: flex-start;
  flex-flow: wrap;
  width: 100%;
  height: 100%;
  &-move {
    transition: transform 1s;
  }
  .ant-card-grid{//小块块
    padding: 12px;
    cursor: pointer;
    >div{
      text-align: left;
      display: flex;
      flex-direction: column;
      overflow-y: scroll;
      overflow-x:hidden;
      height: 100%;
    }
  }
}
.file{
  &-upload{
    ::v-deep .ant-upload-list{//上传文件列表
      display:none;
    }
  }
  &-name{
    font-weight: 700;
  }
}
/deep/.ant-card-head{
  height: @titleHeight;
  min-height: @titleHeight;
  display: flex;
  font-weight: 700;
  .title{
    display: flex;
    align-items: center;
  }
}
.title-icon{
  margin-left: 50px;
  .change-by{
  margin-left: 5px;
  cursor: pointer;
  transition: all 0.4s cubic-bezier(0.645, 0.045, 0.355, 1);
    &:hover{
      color: #1890ff !important;
    }
  }
}
/deep/.ant-card-body{
  height: calc(100vh - @titleHeight - 56px);
  overflow-y: scroll;
}
/deep/.ant-modal-title{
  font-weight: 700;
}

.ant-list {
  /deep/.ant-spin-nested-loading{
    height: calc(350px - 51px - 45px);
    overflow-y: scroll;
  }
  /deep/.ant-list-pagination{
    height: 45px;
    margin: 0;
    display: flex;
    align-items:center;
    border-top: 1px solid #0001;
    justify-content: flex-end;
  }
}
/deep/.ant-spin-dot{
  margin: auto;
}

/deep/.ant-upload-select-text{
  width: 100%;
}


@borderColor:#0001;
.show-targetlist:nth-child(1){
  border-bottom: 1px solid @borderColor;
}
.show-targetlist{
  display: flex;
  justify-content: space-between;
  span{
    text-align: center;
    border-left: 1px solid @borderColor;
  }
  span:nth-child(1){
    width: 100px;
  }
  span:not(:nth-child(1)){
    flex:1;
  }
  span:last-child{
    border-right: 1px solid @borderColor;
  }
}

</style>